import org.apache.kudu.ColumnSchema;
import org.apache.kudu.Schema;
import org.apache.kudu.Type;
import org.apache.kudu.client.*;

import java.util.ArrayList;
import java.util.List;

public class KuduDemo {
    public static void main(String[] args) throws KuduException {
        KuduClient.KuduClientBuilder builder = new KuduClient.KuduClientBuilder("linux100");
        KuduClient client = builder.build();

        // 创建表
        String tableName = "t1";
        List<ColumnSchema>schemaList = new ArrayList<ColumnSchema>();
        ColumnSchema id = new ColumnSchema.ColumnSchemaBuilder("id", Type.INT32).key(true).build();
        ColumnSchema name = new ColumnSchema.ColumnSchemaBuilder("name", Type.STRING).build();
        schemaList.add(id);
        schemaList.add(name);
        Schema schema = new Schema(schemaList);
        CreateTableOptions createTableOptions = new CreateTableOptions();
        createTableOptions.setNumReplicas(1);
        ArrayList<String> colRule = new ArrayList<String>();
        colRule.add("id");
        createTableOptions.addHashPartitions(colRule, 3);
        client.createTable(tableName, schema, createTableOptions);

        KuduTable t1 = client.openTable("t1");

        // 插入记录
        KuduSession kuduSession = client.newSession();
        kuduSession.setFlushMode(SessionConfiguration.FlushMode.MANUAL_FLUSH);
        Insert insert = t1.newInsert();
        insert.getRow().addInt("id", 1);
        insert.getRow().addString("name", "haha");
        kuduSession.flush();
        kuduSession.apply(insert);
        kuduSession.close();

        // 查询记录
        KuduScanner scanner = client.newScannerBuilder(t1).build();
        while (scanner.hasMoreRows()) {
            for (RowResult result: scanner.nextRows()) {
                int rId = result.getInt("id");
                String rName = result.getString("name");
                System.out.println("id:" + rId + ",name:" + rName);
            }
        }

        // 删除表
        client.deleteTable("t1");

        KuduTable dT1 = client.openTable("t1");
        KuduScanner dscanner = client.newScannerBuilder(dT1).build();
        while (dscanner.hasMoreRows()) {
            for (RowResult result: dscanner.nextRows()) {
                int rId = result.getInt("id");
                String rName = result.getString("name");
                System.out.println("id:" + rId + ",name:" + rName);
            }
        }
    }
}
